package routes

import (
	v1 "chat/api/v1"
	"chat/middleware"
	"net/http"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

// SetupRouter 设置路由
func SetupRouter(rootDir string) *gin.Engine {
	r := gin.Default()

	// 静态文件
	r.Static("/static", filepath.Join(rootDir, "static"))

	// HTML模板
	templatePath := filepath.Join(rootDir, "templates", "*.html")
	r.LoadHTMLGlob(templatePath)

	// 页面路由
	r.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "/login")
	})
	r.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.html", nil)
	})
	r.GET("/register", func(c *gin.Context) {
		c.HTML(http.StatusOK, "register.html", nil)
	})
	r.GET("/chat", func(c *gin.Context) {
		c.HTML(http.StatusOK, "chat.html", nil)
	})

	// API路由组
	api := r.Group("/api/v1")

	// 公开路由
	{
		api.POST("/register", v1.NewUserHandler().Register)
		api.POST("/login", v1.NewUserHandler().Login)
	}

	// 需要认证的路由
	auth := api.Use(middleware.JWTAuth())
	{
		// 用户相关
		auth.POST("/logout", v1.NewUserHandler().Logout)
		auth.GET("/user", v1.NewUserHandler().GetUserInfo)
		auth.GET("/users", v1.NewUserHandler().GetUsers)

		// 消息相关
		auth.GET("/messages", v1.NewMessageHandler().GetMessages)

		// WebSocket
		auth.GET("/ws", v1.HandleWebSocket)
	}

	return r
}
